#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
dict builtin 类型的 gtest 测试
"""

import copy
from typing import Any
from gtest import test, EXPECT_EQ, EXPECT_TRUE, EXPECT_FALSE


@test("DictBuiltin", "BasicCreation")
def test_basic_creation():
    """测试字典创建"""
    d = {"a": 1, "b": 2, "c": 3}
    EXPECT_EQ(len(d), 3)


@test("DictBuiltin", "EmptyDict")
def test_empty_dict():
    """测试空字典"""
    d: dict[str, int] = {}  # 明确指定空字典类型
    EXPECT_EQ(len(d), 0)
    EXPECT_FALSE(bool(d))


@test("DictBuiltin", "GetItem")
def test_getitem():
    """测试索引访问"""
    d = {"name": "Alice", "age": 30}
    EXPECT_EQ(d["name"], "Alice")
    EXPECT_EQ(d["age"], 30)


@test("DictBuiltin", "SetItem")
def test_setitem():
    """测试索引赋值"""
    d = {"a": 1}
    d["b"] = 2
    d["a"] = 10
    EXPECT_EQ(d["a"], 10)
    EXPECT_EQ(d["b"], 2)
    EXPECT_EQ(len(d), 2)


@test("DictBuiltin", "Contains")
def test_contains():
    """测试成员检测"""
    d: dict[str, int] = {"x": 1, "y": 2, "z": 3}
    EXPECT_TRUE("x" in d)
    EXPECT_TRUE("y" in d)
    EXPECT_FALSE("w" in d)
    EXPECT_FALSE("a" in d)


@test("DictBuiltin", "GetMethod")
def test_get_method():
    """测试 get 方法"""
    d = {"a": 1, "b": 2}
    EXPECT_EQ(d.get("a", 0), 1)
    EXPECT_EQ(d.get("b", 0), 2)

    # 测试 get 带默认值
    EXPECT_EQ(d.get("c", 99), 99)
    EXPECT_EQ(d.get("a", 99), 1)  # 存在的键返回原值


@test("DictBuiltin", "PopMethod")
def test_pop_method():
    """测试 pop 方法"""
    d = {"a": 1, "b": 2, "c": 3}
    val: int = d.pop("b")  # 现在 pop 返回泛型类型 V
    EXPECT_EQ(val, 2)
    EXPECT_EQ(len(d), 2)
    EXPECT_FALSE("b" in d)

    # 测试 pop 带默认值
    result: int = d.pop("nonexistent", 999)
    EXPECT_EQ(result, 999)
    EXPECT_EQ(len(d), 2)  # 长度不变


@test("DictBuiltin", "Clear")
def test_clear():
    """测试 clear 方法"""
    d = {"a": 1, "b": 2, "c": 3}
    d.clear()
    EXPECT_EQ(len(d), 0)
    EXPECT_FALSE(bool(d))  # 清空后字典为假值


@test("DictBuiltin", "Update")
def test_update():
    """测试 update 方法"""
    d1 = {"a": 1, "b": 2}
    d2 = {"c": 3, "d": 4}
    d1.update(d2)
    EXPECT_EQ(len(d1), 4)
    EXPECT_EQ(d1["c"], 3)
    EXPECT_EQ(d1["d"], 4)


@test("DictBuiltin", "Copy")
def test_copy():
    """测试 copy 方法创建独立的顶层字典"""
    d1 = {"a": 1, "b": 2, "c": 3}
    d2 = d1.copy()
    EXPECT_EQ(d1, d2)
    EXPECT_EQ(len(d2), 3)

    # 修改副本的顶层键值对，不应影响原字典
    d2["a"] = 100
    d2["d"] = 4
    EXPECT_EQ(d1["a"], 1)  # 原字典未被修改
    EXPECT_EQ(len(d1), 3)  # 原字典长度未变
    EXPECT_EQ(d2["a"], 100)  # 副本已修改
    EXPECT_EQ(len(d2), 4)  # 副本长度增加


@test("DictBuiltin", "Equality")
def test_equality():
    """测试相等比较"""
    d1: dict[str, int] = {"a": 1, "b": 2}
    d2: dict[str, int] = {"a": 1, "b": 2}
    d3: dict[str, int] = {"a": 1, "b": 3}

    EXPECT_TRUE(d1 == d2)
    EXPECT_FALSE(d1 == d3)
    EXPECT_FALSE(d1 != d2)
    EXPECT_TRUE(d1 != d3)


@test("DictBuiltin", "InsertionOrder")
def test_insertion_order():
    """测试插入顺序（Python 3.7+ 特性）"""
    d: dict[str, int] = {}  # 明确指定空字典类型
    d["third"] = 3
    d["first"] = 1
    d["second"] = 2

    keys_list: list[str] = list(d.keys())
    EXPECT_EQ(len(keys_list), 3)
    EXPECT_EQ(keys_list[0], "third")
    EXPECT_EQ(keys_list[1], "first")
    EXPECT_EQ(keys_list[2], "second")


@test("DictBuiltin", "Keys")
def test_keys():
    """测试 keys 方法"""
    d = {"a": 1, "b": 2, "c": 3}
    keys_list: list[str] = list(d.keys())  # 直接转换为 list
    EXPECT_EQ(len(keys_list), 3)
    EXPECT_EQ(keys_list[0], "a")
    EXPECT_EQ(keys_list[1], "b")
    EXPECT_EQ(keys_list[2], "c")


@test("DictBuiltin", "Values")
def test_values():
    """测试 values 方法"""
    d = {"a": 1, "b": 2, "c": 3}
    # 直接转换为 list 验证
    values_list: list[int] = list(d.values())
    EXPECT_EQ(len(values_list), 3)
    EXPECT_EQ(values_list[0], 1)
    EXPECT_EQ(values_list[1], 2)
    EXPECT_EQ(values_list[2], 3)
    for value in d.values():
        EXPECT_TRUE(value in values_list)


@test("DictBuiltin", "Items")
def test_items():
    """测试 items 方法"""
    d = {"a": 1, "b": 2}
    # 直接转换为 list 验证
    items_list: list[tuple[str, int]] = list(d.items())
    EXPECT_EQ(len(items_list), 2)

    # 验证元组访问 - 常量索引（编译时）
    first_item: tuple[str, int] = items_list[0]
    EXPECT_EQ(first_item[0], "a")
    EXPECT_EQ(first_item[1], 1)

    a = first_item[0]
    b = first_item[1]
    EXPECT_EQ(a, "a")
    EXPECT_EQ(b, 1)

    # 非常量索引访问强类型 tuple 会使用运行时版本
    idx_0 = 0
    idx_1 = 1
    aa: str = first_item[idx_0]
    bb: int = first_item[idx_1]
    EXPECT_EQ(aa, "a")
    EXPECT_EQ(bb, 1)

    second_item: tuple[str, int] = items_list[1]
    EXPECT_EQ(second_item[0], "b")
    EXPECT_EQ(second_item[1], 2)

    # 验证元组访问 - 非常量索引（运行时）
    for i in range(2):
        item: tuple[str, int] = items_list[i]
        key: str = item[0]  # 常量索引
        value: int = item[1]  # 常量索引
        EXPECT_TRUE(key == "a" or key == "b")
        EXPECT_TRUE(value == 1 or value == 2)

    # 测试运行时索引访问
    idx: int = 0
    test_item: tuple[str, int] = items_list[0]
    # 非常量索引访问强类型 tuple 会使用运行时版本
    first_elem: Any = test_item[idx]  # 运行时索引，返回 mc::variant
    EXPECT_EQ(first_elem, "a")


@test("DictBuiltin", "BooleanValue")
def test_boolean_value():
    """测试布尔值转换"""
    empty: dict[str, int] = {}
    non_empty: dict[str, int] = {"a": 1}

    EXPECT_FALSE(bool(empty))
    EXPECT_TRUE(bool(non_empty))


@test("DictBuiltin", "LengthOperations")
def test_length():
    """测试长度操作"""
    d: dict[str, int] = {}  # 明确指定空字典类型
    EXPECT_EQ(len(d), 0)

    d["a"] = 1
    EXPECT_EQ(len(d), 1)

    d["b"] = 2
    d["c"] = 3
    EXPECT_EQ(len(d), 3)


@test("DictBuiltin", "OverwriteValue")
def test_overwrite():
    """测试覆盖已存在的键"""
    d = {"a": 1, "b": 2}
    d["a"] = 100
    EXPECT_EQ(d["a"], 100)
    EXPECT_EQ(len(d), 2)  # 长度不变


@test("DictBuiltin", "IntegerKeys")
def test_integer_keys():
    """测试整数键"""
    d = {1: "one", 2: "two", 3: "three"}
    EXPECT_EQ(d[1], "one")
    EXPECT_EQ(d[2], "two")
    EXPECT_TRUE(1 in d)
    EXPECT_FALSE(4 in d)


@test("DictBuiltin", "MixedTypes")
def test_mixed_types():
    """测试混合类型的字典"""
    d = {"name": "Alice", "age": 30, "active": True}
    EXPECT_EQ(d["name"], "Alice")
    EXPECT_EQ(d["age"], 30)
    EXPECT_EQ(d["active"], True)


@test("DictBuiltin", "DelItem")
def test_delitem():
    """测试 del 删除操作"""
    d = {"a": 1, "b": 2, "c": 3}
    del d["b"]
    EXPECT_EQ(len(d), 2)
    EXPECT_FALSE("b" in d)
    EXPECT_TRUE("a" in d)
    EXPECT_TRUE("c" in d)


@test("DictBuiltin", "PopItem")
def test_popitem():
    """测试 popitem 方法（删除并返回最后插入的键值对）"""
    d = {"a": 1, "b": 2, "c": 3}
    # popitem 返回最后插入的键值对
    item: tuple[str, int] = d.popitem()
    EXPECT_EQ(len(d), 2)
    # 验证返回的元组内容（应该是最后插入的"c": 3）
    EXPECT_EQ(item[0], "c")
    EXPECT_EQ(item[1], 3)

    # 再次 popitem
    item2: tuple[str, int] = d.popitem()
    EXPECT_EQ(len(d), 1)
    EXPECT_EQ(item2[0], "b")
    EXPECT_EQ(item2[1], 2)


@test("DictBuiltin", "Setdefault")
def test_setdefault():
    """测试 setdefault 方法"""
    d = {"a": 1, "b": 2}

    # 键存在，返回现有值（setdefault 返回 variant&，不指定类型）
    d.setdefault("a", 999)
    EXPECT_EQ(d["a"], 1)  # 值没有被修改
    EXPECT_EQ(len(d), 2)

    # 键不存在，插入默认值并返回
    d.setdefault("c", 3)
    EXPECT_EQ(d["c"], 3)  # 新键被插入
    EXPECT_EQ(len(d), 3)
    EXPECT_TRUE("c" in d)
    EXPECT_EQ(d["c"], 3)


@test("DictBuiltin", "MergeOperator")
def test_merge_operator():
    """测试 | 合并运算符（Python 3.9+）"""
    d1: dict[str, int] = {"a": 1, "b": 2}
    d2: dict[str, int] = {"c": 3, "d": 4}
    d3: dict[str, int] = d1 | d2

    EXPECT_EQ(len(d3), 4)
    EXPECT_EQ(d3["a"], 1)
    EXPECT_EQ(d3["b"], 2)
    EXPECT_EQ(d3["c"], 3)
    EXPECT_EQ(d3["d"], 4)

    a = d1["a"]
    EXPECT_EQ(a, 1)

    b = d1["a"] * 2 + 100
    EXPECT_EQ(b, 102)

    # 原字典不变
    EXPECT_EQ(len(d1), 2)
    EXPECT_EQ(len(d2), 2)


@test("DictBuiltin", "InplaceMergeOperator")
def test_ior_operator():
    """测试 |= 就地合并运算符（Python 3.9+）"""
    d1: dict[str, int] = {"a": 1, "b": 2}
    d2: dict[str, int] = {"c": 3, "d": 4}
    d1 |= d2

    EXPECT_EQ(len(d1), 4)
    EXPECT_EQ(d1["a"], 1)
    EXPECT_EQ(d1["c"], 3)


@test("DictBuiltin", "MergeWithOverlap")
def test_merge_with_overlap():
    """测试合并运算符处理重叠键"""
    d1: dict[str, int] = {"a": 1, "b": 2}
    d2: dict[str, int] = {"b": 20, "c": 3}
    d3: dict[str, int] = d1 | d2

    # 右侧字典的值应覆盖左侧
    EXPECT_EQ(d3["a"], 1)
    EXPECT_EQ(d3["b"], 20)  # 被 d2 覆盖
    EXPECT_EQ(d3["c"], 3)
    EXPECT_EQ(len(d3), 3)


@test("DictBuiltin", "ForInLoop")
def test_for_in_loop():
    """测试 for-in 循环遍历字典（遍历键）"""
    d = {"a": 1, "b": 2, "c": 3, 2: 4}
    count = 0

    # 直接迭代字典迭代的是 d.keys()
    for key in d:
        count += d[key]
    EXPECT_EQ(count, 10)

    # 直接迭代字典迭代的 d.keys()
    count = 0
    for key in d.keys():
        count += d[key]
    EXPECT_EQ(count, 10)


@test("DictBuiltin", "NestedDict")
def test_nested_dict():
    """测试基本嵌套字典"""
    # 创建嵌套字典
    d = {"user": {"name": "Alice", "age": 30}, "settings": {"theme": "dark"}}

    # 验证外层字典
    EXPECT_EQ(len(d), 2)
    EXPECT_TRUE("user" in d)
    EXPECT_TRUE("settings" in d)

    # 测试链式访问嵌套值
    user_name = d["user"]["name"]
    EXPECT_EQ(user_name, "Alice")

    user_age = d["user"]["age"]
    EXPECT_EQ(user_age, 30)

    settings_theme = d["settings"]["theme"]
    EXPECT_EQ(settings_theme, "dark")

    # 测试三层嵌套访问
    nested3 = {"level1": {"level2": {"level3": "deep"}}}
    EXPECT_EQ(nested3["level1"]["level2"]["level3"], "deep")


@test("DictBuiltin", "GetNestedDict")
def test_get_nested_dict():
    """测试获取嵌套字典后的操作"""
    d = {"user": {"name": "Alice", "age": 30}}

    # 获取嵌套字典 - 应自动转换为 dict
    user: dict = d["user"]

    # 对嵌套字典进行操作
    EXPECT_EQ(len(user), 2)
    EXPECT_TRUE("name" in user)
    EXPECT_EQ(user["name"], "Alice")
    EXPECT_EQ(user["age"], 30)


@test("DictBuiltin", "IterateNestedDict")
def test_iterate_nested_dict():
    """测试遍历嵌套字典"""
    d = {"user": {"name": "Alice", "age": 30}}

    # 获取嵌套字典
    user: dict = d["user"]

    # 遍历键
    keys = list(user.keys())
    EXPECT_EQ(len(keys), 2)

    # 遍历值
    values = list(user.values())
    EXPECT_EQ(len(values), 2)


@test("DictBuiltin", "DeepNested")
def test_deep_nested():
    """测试深层嵌套（4层）"""
    d = {"level1": {"level2": {"level3": {"data": "deep_value"}}}}

    # 链式访问深层数据
    EXPECT_EQ(d["level1"]["level2"]["level3"]["data"], "deep_value")

    # 逐层获取
    level1: dict = d["level1"]
    EXPECT_TRUE("level2" in level1)

    level2: dict = level1["level2"]
    EXPECT_TRUE("level3" in level2)

    level3: dict = level2["level3"]
    EXPECT_EQ(level3["data"], "deep_value")


@test("DictBuiltin", "NestedDictCheck")
def test_nested_dict_check():
    """测试嵌套字典存在性检查"""
    d = {"outer": {"inner": {"value": 123}}}

    # 检查嵌套键
    EXPECT_TRUE("outer" in d)

    outer: dict = d["outer"]
    EXPECT_TRUE("inner" in outer)

    inner: dict = outer["inner"]
    EXPECT_TRUE("value" in inner)
    EXPECT_FALSE("missing" in inner)


@test("DictBuiltin", "NestedWithEmptyDict")
def test_nested_with_empty_dict():
    """测试包含空字典的嵌套"""
    d = {"data": {"items": {}, "count": 0}}

    data: dict = d["data"]
    items: dict = data["items"]

    EXPECT_EQ(len(items), 0)
    EXPECT_FALSE(bool(items))
    EXPECT_EQ(data["count"], 0)


@test("DictBuiltin", "ModifyNestedDict")
def test_modify_nested_dict():
    """测试修改嵌套字典是否影响原字典（引用语义）"""
    d = {"user": {"name": "Alice", "age": 30}}

    # 获取嵌套字典（会调用 as_mutable_dict()）
    user: dict = d["user"]

    # 修改user
    user["age"] = 31
    user["city"] = "Beijing"

    # 检查原字典d是否被修改
    # 由于dict使用共享数据模型，修改应该影响原字典
    EXPECT_EQ(d["user"]["age"], 31)
    EXPECT_TRUE("city" in d["user"])


@test("DictBuiltin", "MultipleReferences")
def test_multiple_references():
    """测试多个引用的修改行为"""
    d = {"data": {"value": 100}}

    # 创建两个引用
    ref1: dict = d["data"]
    ref2: dict = d["data"]

    # 通过ref1修改
    ref1["value"] = 200

    # 检查ref2和d是否都被修改（共享引用语义）
    EXPECT_EQ(ref2["value"], 200)
    EXPECT_EQ(d["data"]["value"], 200)


@test("DictBuiltin", "ChainAssignment")
def test_chain_assignment():
    """测试链式赋值（直接修改嵌套值）"""
    d = {"user": {"name": "Alice", "age": 30}}

    # 链式修改 - 应该支持
    d["user"]["name"] = "Bob"
    EXPECT_EQ(d["user"]["name"], "Bob")

    d["user"]["age"] = 31
    EXPECT_EQ(d["user"]["age"], 31)

    # 添加新键
    d["user"]["city"] = "Beijing"
    EXPECT_TRUE("city" in d["user"])
    EXPECT_EQ(d["user"]["city"], "Beijing")


@test("DictBuiltin", "DeepChainAssignment")
def test_deep_chain_assignment():
    """测试深层链式赋值"""
    d = {"level1": {"level2": {"level3": {"data": "old"}}}}

    # 深层链式修改
    d["level1"]["level2"]["level3"]["data"] = "new"
    EXPECT_EQ(d["level1"]["level2"]["level3"]["data"], "new")

    # 添加深层新键
    d["level1"]["level2"]["level3"]["extra"] = "added"
    EXPECT_TRUE("extra" in d["level1"]["level2"]["level3"])


@test("DictBuiltin", "ChainAssignmentMixed")
def test_chain_assignment_mixed():
    """测试链式赋值与中间变量混合使用"""
    d = {"config": {"server": {"host": "localhost", "port": 8080}}}

    # 链式修改
    d["config"]["server"]["host"] = "127.0.0.1"
    EXPECT_EQ(d["config"]["server"]["host"], "127.0.0.1")

    # 中间变量修改
    server: dict = d["config"]["server"]
    server["port"] = 9000

    # 验证链式和中间变量修改都生效
    EXPECT_EQ(d["config"]["server"]["host"], "127.0.0.1")
    EXPECT_EQ(d["config"]["server"]["port"], 9000)


@test("DictBuiltin", "EmptyDictOperations")
def test_empty_dict_operations():
    """测试空字典的各种操作"""
    d: dict[str, int] = {}  # 明确指定空字典类型

    EXPECT_EQ(len(d), 0)
    EXPECT_FALSE(bool(d))
    EXPECT_FALSE("any_key" in d)

    # 对空字典调用方法
    d.clear()  # 应该不会出错
    EXPECT_EQ(len(d), 0)

    # 空字典的 keys() 和 values()
    EXPECT_EQ(len(list(d.keys())), 0)
    EXPECT_EQ(len(list(d.values())), 0)


@test("DictBuiltin", "ViewIteration")
def test_view_iteration():
    """测试视图对象的迭代功能"""
    d = {"a": 1, "b": 2, "c": 3}

    # 迭代 keys
    count = 0
    for key in d.keys():
        count = count + 1
    EXPECT_EQ(count, 3)

    # 迭代 values
    sum_val = 0
    for val in d.values():
        sum_val = sum_val + val
    EXPECT_EQ(sum_val, 6)

    # 迭代 items
    item_count = 0
    for item in d.items():
        item_count = item_count + 1
    EXPECT_EQ(item_count, 3)


@test("DictBuiltin", "ViewConversion")
def test_view_conversion():
    """测试视图对象转换为 list"""
    d = {"apple": 1, "banana": 2, "cherry": 3}

    # 测试 keys 转换
    keys_list: list[str] = list(d.keys())
    EXPECT_EQ(len(keys_list), 3)
    EXPECT_EQ(keys_list[0], "apple")
    EXPECT_TRUE("apple" in keys_list)
    EXPECT_TRUE("banana" in keys_list)
    EXPECT_FALSE("durian" in keys_list)

    # 测试 values 转换
    values_list: list[int] = list(d.values())
    EXPECT_EQ(len(values_list), 3)
    EXPECT_EQ(values_list[0], 1)
    EXPECT_EQ(values_list[1], 2)

    # 测试 items 转换
    items_list: list[tuple[str, int]] = list(d.items())
    EXPECT_EQ(len(items_list), 3)


@test("DictBuiltin", "EmptyDictViews")
def test_empty_dict_views():
    """测试空字典的视图对象"""
    d: dict[str, int] = {}

    keys_list: list[str] = list(d.keys())
    values_list: list[int] = list(d.values())
    items_list: list[tuple[str, int]] = list(d.items())

    EXPECT_EQ(len(keys_list), 0)
    EXPECT_EQ(len(values_list), 0)
    EXPECT_EQ(len(items_list), 0)


@test("DictBuiltin", "FromKeys")
def test_fromkeys():
    """测试 dict.fromkeys() 类方法"""
    keys = ["a", "b", "c"]
    d1: dict[str, int] = dict.fromkeys(keys, 0)

    EXPECT_EQ(len(d1), 3)
    EXPECT_EQ(d1["a"], 0)
    EXPECT_EQ(d1["b"], 0)
    EXPECT_EQ(d1["c"], 0)


@test("DictBuiltin", "ComprehensionBasic")
def test_dict_comprehension_basic():
    """测试基本字典推导式"""
    nums: list[int] = [1, 2, 3]
    d1: dict[int, int] = {x: x * 2 for x in nums}
    EXPECT_EQ(len(d1), 3)
    EXPECT_EQ(d1[1], 2)


@test("DictBuiltin", "ComprehensionConditional")
def test_dict_comprehension_conditional():
    """测试带条件的字典推导式"""
    nums: list[int] = [1, 2, 3, 4, 5]
    d1: dict[int, int] = {x: x * 2 for x in nums if x % 2 == 0}
    EXPECT_EQ(len(d1), 2)
    EXPECT_EQ(d1[2], 4)


@test("DictBuiltin", "StringRepresentation")
def test_dict_string_representation():
    """测试字典的字符串表示"""
    d1: dict[str, int] = {"a": 1, "b": 2}

    # 测试 repr() 全局函数（推荐方式）
    repr_str: str = repr(d1)
    EXPECT_EQ(len(repr_str) > 0, True)

    # 测试 __repr__ 方法（直接调用，不推荐但也应该支持）
    repr_str2: str = d1.__repr__()
    EXPECT_EQ(len(repr_str2) > 0, True)

    # 空字典的表示
    empty: dict[str, int] = {}
    empty_repr: str = repr(empty)
    EXPECT_EQ(len(empty_repr) > 0, True)


@test("DictBuiltin", "SafeAccess")
def test_dict_safe_access():
    """测试字典的安全访问方法"""
    d: dict[str, int] = {"a": 1, "b": 2}

    # 使用 get() 方法访问存在的键
    val1: int = d.get("a", -1)
    EXPECT_EQ(val1, 1)

    # 使用 get() 方法访问不存在的键（使用默认值）
    val2: int = d.get("nonexistent", -1)
    EXPECT_EQ(val2, -1)

    # 使用 in 检查后再访问
    if "a" in d:
        EXPECT_EQ(d["a"], 1)

    # 检查不存在的键
    exists: bool = "nonexistent" in d
    EXPECT_EQ(exists, False)


@test("DictBuiltin", "ReversedIteration")
def test_reversed_iteration():
    """测试反向迭代字典（Python 3.8+）"""
    d: dict[str, int] = {}
    d["first"] = 1
    d["second"] = 2
    d["third"] = 3

    # 反向迭代 - 直接在循环中使用（左值引用版本）
    count = 0
    expected = ["third", "second", "first"]
    for key in reversed(d):
        # 验证顺序
        EXPECT_EQ(key, expected[count])
        count += 1

    # 测试字典字面量的反向迭代（右值拷贝版本）
    # 字典字面量被推导为弱类型 dict，键为 mc::variant
    literal_keys = []
    for key in reversed({"a": 1, "b": 2, "c": 3}):
        literal_keys.append(key)
    # dict 保持插入顺序，反向应该是 c, b, a
    EXPECT_EQ(len(literal_keys), 3)

    EXPECT_EQ(count, 3)


@test("DictBuiltin", "DeepCopy")
def test_deepcopy():
    """测试字典深度拷贝（使用 copy.deepcopy）"""
    # 创建嵌套字典
    d = {"user": {"name": "Alice", "age": 30}}

    # 深度拷贝
    d_copy = copy.deepcopy(d)

    # 验证拷贝成功
    EXPECT_EQ(len(d_copy), 1)
    EXPECT_EQ(d_copy["user"]["name"], "Alice")

    # 修改拷贝的嵌套字典
    user_copy: dict = d_copy["user"]
    user_copy["name"] = "Bob"
    user_copy["age"] = 25

    # 验证原字典未被修改（深拷贝）
    EXPECT_EQ(d["user"]["name"], "Alice")
    EXPECT_EQ(d["user"]["age"], 30)

    # 验证拷贝已修改
    EXPECT_EQ(d_copy["user"]["name"], "Bob")
    EXPECT_EQ(d_copy["user"]["age"], 25)


@test("DictBuiltin", "ShallowVsDeepCopy")
def test_shallow_vs_deep_copy():
    """测试浅拷贝 vs 深度拷贝的区别"""
    d = {"nested": {"value": 100}}

    # 浅拷贝 - 共享嵌套对象
    d_shallow = copy.copy(d)
    # 直接使用字典自带的 dict.copy 方法也是浅拷贝
    d_copy = d.copy()

    nested_shallow: dict = d_shallow["nested"]
    nested_shallow["value"] = 200
    EXPECT_EQ(d["nested"]["value"], 200)  # 原字典被修改（共享引用）
    EXPECT_EQ(d_copy["nested"]["value"], 200)  # 原字典被修改（共享引用）

    # 重置
    d = {"nested": {"value": 100}}

    # 深拷贝
    d_deep = copy.deepcopy(d)
    nested_deep: dict = d_deep["nested"]
    nested_deep["value"] = 300
    EXPECT_EQ(d["nested"]["value"], 100)  # 原字典未修改
    EXPECT_EQ(d_deep["nested"]["value"], 300)  # 拷贝已修改


def get_test_dict() -> dict[str, int]:
    """辅助函数：返回一个测试字典（用于验证临时对象处理）"""
    return {"apple": 100, "banana": 200, "cherry": 300}


def get_merged_dict() -> dict[int, str]:
    """辅助函数：返回合并后的字典（模拟表达式结果）"""
    d1: dict[int, str] = {1: "a", 2: "b"}
    d2: dict[int, str] = {3: "c", 4: "d"}
    return d1 | d2


@test("DictBuiltin", "DictViewsTemporaryObjects")
def test_dict_views_temporary_objects():
    """测试字典视图是否正确处理临时对象生命周期"""

    # 场景1：字面量字典的 keys()
    result_keys: list[int] = []
    for key in {1: "a", 2: "b", 3: "c"}.keys():
        result_keys.append(key)
    EXPECT_EQ(len(result_keys), 3)
    EXPECT_TRUE(1 in result_keys)
    EXPECT_TRUE(2 in result_keys)
    EXPECT_TRUE(3 in result_keys)

    # 场景2：字面量字典的 values()
    result_vals: list[str] = []
    for val in {1: "x", 2: "y"}.values():
        result_vals.append(val)
    EXPECT_EQ(len(result_vals), 2)
    EXPECT_TRUE("x" in result_vals)
    EXPECT_TRUE("y" in result_vals)

    # 场景3：字面量字典的 items()
    result_items: list[tuple[int, str]] = []
    for item in {10: "foo", 20: "bar"}.items():
        result_items.append(item)
    EXPECT_EQ(len(result_items), 2)
    EXPECT_EQ(result_items[0], (10, "foo"))
    EXPECT_EQ(result_items[1], (20, "bar"))

    # 场景4：函数返回的临时字典 - keys() 直接链式调用
    # 这是最关键的测试场景：临时对象立即调用方法
    func_result_keys: list = []
    for key in get_test_dict().keys():
        func_result_keys.append(key)
    EXPECT_EQ(len(func_result_keys), 3)

    # 场景5：函数返回的临时字典 - values() 直接链式调用
    func_result_vals: list = []
    for val in get_test_dict().values():
        func_result_vals.append(val)
    EXPECT_EQ(len(func_result_vals), 3)

    # 场景6：函数返回的临时字典 - items() 直接链式调用
    func_result_items: list = []
    for item in get_test_dict().items():
        func_result_items.append(item)
    EXPECT_EQ(len(func_result_items), 3)

    # 场景7：合并操作返回的临时字典 - 直接链式调用
    merged_result: list = []
    for item in get_merged_dict().items():
        merged_result.append(item)
    EXPECT_EQ(len(merged_result), 4)


# ============================================================================
# enumerate 视图类型测试
# ============================================================================


@test("DictBuiltin", "EnumerateDictKeys")
def test_enumerate_dict_keys():
    """测试 enumerate(dict.keys()) - 枚举字典键视图"""
    d: dict[str, int] = {"a": 1, "b": 2, "c": 3}

    result: list[tuple[int, str]] = []
    for idx, key in enumerate(d.keys()):
        result.append((idx, key))

    expected = [(0, "a"), (1, "b"), (2, "c")]
    EXPECT_EQ(result, expected)


@test("DictBuiltin", "EnumerateDictValues")
def test_enumerate_dict_values():
    """测试 enumerate(dict.values()) - 枚举字典值视图"""
    d: dict[str, int] = {"a": 1, "b": 2, "c": 3}

    result: list[tuple[int, int]] = []
    for idx, val in enumerate(d.values()):
        result.append((idx, val))
    expected = [(0, 1), (1, 2), (2, 3)]
    EXPECT_EQ(result, expected)


@test("DictBuiltin", "EnumerateDictItems")
def test_enumerate_dict_items():
    """测试 enumerate(dict.items()) - 枚举字典项视图"""
    d: dict[str, int] = {"a": 1, "b": 2, "c": 3}

    result: list[tuple[int, tuple[str, int]]] = []
    for idx, item in enumerate(d.items()):
        result.append((idx, item))

    expected = [
        (0, ("a", 1)),
        (1, ("b", 2)),
        (2, ("c", 3)),
    ]
    EXPECT_EQ(result, expected)


# TODO: 未来增强
# ❌ DEFER: test_key_error_exception - 需要完整的异常处理系统
#    当前可以使用 get() 方法或 in 检查作为替代方案
